<script setup lang="ts">
import type { FormRules } from 'element-plus'
import { onMounted, reactive, ref } from 'vue'

interface Props {
  data?: Record<string, any> | never | null
  status?: string | never | null
}

const { data = null } = defineProps<Props>()

const baseFormRef = ref()

const form = ref<Record<string, any>>({})

const rules = reactive<FormRules>({
  name: [{ required: true, message: '昵称不能为空!', trigger: 'blur' }],
  username: [{ required: true, message: '用户名不能为空!', trigger: 'blur' }],
  password: [{ required: true, message: '密码不能为空!', trigger: 'blur' }],
})

const initForm = () => {
  if (data) {
    Object.keys(data).forEach((key: string) => {
      if (key == 'roles') {
        form.value.roleid = data![key][0].id
      } else {
        form.value[key] = data![key]
      }
    })
  }
}

const formatForm = () => {
  const result: Record<string, any> = {}
  Object.keys(form.value).forEach((key: string) => {
    result[key] = form.value[key]
  })
  return result
}

const submitForm = () => {
  return baseFormRef.value.submit(formatForm)
}

defineExpose({
  submitForm,
})

onMounted(() => {
  initForm()
})
</script>

<template>
  <BaseForm
    ref="baseFormRef"
    :form="form"
    :rules="rules"
    width="320px"
    :attributes="{ 'label-width': '100px' }"
  >
    <el-form-item label="昵称:" prop="name">
      <el-input
        v-model="form.name"
        type="text"
        placeholder="请输入内容"
        maxlength="20"
        show-word-limit
      >
      </el-input>
    </el-form-item>
    <el-form-item label="用户名:" prop="username">
      <el-input
        v-model="form.username"
        type="text"
        placeholder="请输入内容"
        maxlength="20"
        show-word-limit
      >
      </el-input>
    </el-form-item>
    <el-form-item label="密码:" prop="password">
      <el-input
        v-model="form.password"
        type="text"
        placeholder="请输入内容"
        maxlength="20"
        show-word-limit
        show-password
      >
      </el-input>
    </el-form-item>
  </BaseForm>
</template>

<style lang="scss" scoped></style>
